package com.haha.keymap.v1;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

/**
 * @author shenlinnan
 * @date 2025/7/6 0:49
 */
public class KeyRemapper implements NativeKeyListener {

    /**
     * 原始按键（1）
     */
    private static final int ORIGINAL_KEY = NativeKeyEvent.VC_Q;
    /**
     * 映射按键（3）
     */
    private static final int MAPPED_KEY = KeyEvent.VK_3;
    private final Robot robot;
    /**
     * 添加处理状态标记
     */
    private volatile boolean keyProcessed = false;

    private final SkillConfigData skillConfigData;
    private final SkillConfigData aoeSkillConfigData;

    public KeyRemapper() throws AWTException {
        robot = new Robot();
        skillConfigData = getConfigInfo();
        aoeSkillConfigData = getAoeConfigInfo();
        if (skillConfigData == null) {
            System.out.println("未读取到配置");
        } else {
            System.out.println(skillConfigData.toString());
        }
        // 按键间延迟
        robot.setAutoDelay(10);
    }

    public static void main(String[] args) {
        try {
            // 设置全局键盘钩子
            GlobalScreen.registerNativeHook();
            GlobalScreen.addNativeKeyListener(new KeyRemapper());

            // 禁用JNativeHook日志
            java.util.logging.Logger.getLogger(GlobalScreen.class.getPackage().getName())
                    .setLevel(java.util.logging.Level.OFF);

            //System.out.println("按键映射已启动 (1 -> 3)");

            // 保持程序运行
            Thread.currentThread().join();
        } catch (NativeHookException | InterruptedException | AWTException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void nativeKeyPressed(NativeKeyEvent e) {
        if (e.getKeyCode() == NativeKeyEvent.VC_Q) {
            try {
                if (skillConfigData == null) {
                    System.out.println("未读取到配置");
                    return;
                }
                List<CustomPoint> pointList = skillConfigData.getPoint();

                List<SkillInfo> skills = skillConfigData.getSkills();
                System.out.println(skills);

                for (int i = 0; i < skills.size(); i++) {
                    boolean match = true;
                    SkillInfo skillInfo = skills.get(i);
                    List<CustomColor> color = skillInfo.getColor();
                    System.out.println("执行了" + (i + 1) + "次");

                    for (int j = 0; j < color.size(); j++) {
                        CustomPoint customPoint = pointList.get(j);
                        int x = customPoint.getX();
                        int y = customPoint.getY();
                        Color currentColor = robot.getPixelColor(x, y);

                        CustomColor customColor = color.get(j);
                        System.out.println(customColor);
                        System.out.println(currentColor);
                        if (!customColor.compare(currentColor)) {
                            match = false;
                            System.out.println("不匹配");
                            break;
                        }
                    }
                    if (!match) {
                        continue;
                    }
                    String keyBinding = skillInfo.getKeyBinding();
                    // 释放原始按键
                    robot.keyRelease(KeyEvent.VK_Q);
                    // 标记已处理（防止后续重复处理）
                    keyProcessed = true;

                    if ("-".equals(keyBinding)) {
                        robot.keyPress(KeyEvent.VK_MINUS);
                    }
                    if ("=".equals(keyBinding)) {
                        System.out.println("按了.......");
                        robot.keyPress(KeyEvent.VK_EQUALS);
                    }
                    if ("3".equals(keyBinding)) {
                        System.out.println("按了.......");
                        robot.keyPress(KeyEvent.VK_3);
                    }
                    if ("4".equals(keyBinding)) {
                        System.out.println("按了.......");
                        robot.keyPress(KeyEvent.VK_4);
                    }
                    break;

                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        if (e.getKeyCode() == NativeKeyEvent.VC_E) {
            try {
                if (aoeSkillConfigData == null) {
                    System.out.println("未读取到配置");
                    return;
                }
                List<CustomPoint> pointList = aoeSkillConfigData.getPoint();

                List<SkillInfo> skills = aoeSkillConfigData.getSkills();
                System.out.println(skills);

                for (int i = 0; i < skills.size(); i++) {
                    boolean match = true;
                    SkillInfo skillInfo = skills.get(i);
                    List<CustomColor> color = skillInfo.getColor();
                    System.out.println("执行了" + (i + 1) + "次");

                    for (int j = 0; j < color.size(); j++) {
                        CustomPoint customPoint = pointList.get(j);
                        int x = customPoint.getX();
                        int y = customPoint.getY();
                        Color currentColor = robot.getPixelColor(x, y);

                        CustomColor customColor = color.get(j);
                        System.out.println(customColor);
                        System.out.println(currentColor);
                        if (!customColor.compare(currentColor)) {
                            match = false;
                            System.out.println("不匹配");
                            break;
                        }
                    }
                    if (!match) {
                        continue;
                    }
                    String keyBinding = skillInfo.getKeyBinding();
                    // 释放原始按键
                    robot.keyRelease(KeyEvent.VK_Q);
                    // 标记已处理（防止后续重复处理）
                    keyProcessed = true;

                    if ("-".equals(keyBinding)) {
                        robot.keyPress(KeyEvent.VK_MINUS);
                    }
                    if ("=".equals(keyBinding)) {
                        System.out.println("按了.......");
                        robot.keyPress(KeyEvent.VK_EQUALS);
                    }
                    if ("3".equals(keyBinding)) {
                        System.out.println("按了.......");
                        robot.keyPress(KeyEvent.VK_3);
                    }
                    if ("4".equals(keyBinding)) {
                        System.out.println("按了.......");
                        robot.keyPress(KeyEvent.VK_4);
                    }
                    if ("2".equals(keyBinding)) {
                        System.out.println("按了.......");
                        robot.keyPress(KeyEvent.VK_2);
                    }
                    break;

                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    private SkillConfigData getConfigInfo() {
        // 1. 读取JSON文件
        String filePath = "I:\\my-workspace\\haha-maven\\src\\main\\java\\com\\haha\\keymap\\v1\\config.json";

        // 2. 创建 Gson 实例（带格式化输出）
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        try (FileReader reader = new FileReader(filePath)) {
            // 3. 定义 JSON 结构对应的 Java 类型
            Type configType = new TypeToken<SkillConfigData>() {
            }.getType();

            // 4. 解析 JSON 到 Java 对象
            return gson.fromJson(reader, configType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private SkillConfigData getAoeConfigInfo() {
        // 1. 读取JSON文件
        String filePath = "I:\\my-workspace\\haha-maven\\src\\main\\java\\com\\haha\\keymap\\v1\\aoe_config.json";

        // 2. 创建 Gson 实例（带格式化输出）
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        try (FileReader reader = new FileReader(filePath)) {
            // 3. 定义 JSON 结构对应的 Java 类型
            Type configType = new TypeToken<SkillConfigData>() {
            }.getType();

            // 4. 解析 JSON 到 Java 对象
            return gson.fromJson(reader, configType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void releaseAllMappedKeys() {
        for (MappedKey key : MappedKey.values()) {
            robot.keyRelease(key.keyCode);
        }
    }

    @Override
    public void nativeKeyReleased(NativeKeyEvent e) {
        if (e.getKeyCode() == ORIGINAL_KEY && keyProcessed) {
            try {
                robot.keyRelease(MAPPED_KEY);
                robot.keyRelease(KeyEvent.VK_0);
                robot.keyRelease(KeyEvent.VK_9);
                robot.keyRelease(KeyEvent.VK_MINUS);
                robot.keyRelease(KeyEvent.VK_1);
                robot.keyRelease(KeyEvent.VK_2);
                robot.keyRelease(KeyEvent.VK_3);
                robot.keyRelease(KeyEvent.VK_4);
                robot.keyRelease(KeyEvent.VK_EQUALS);
                // 重置状态
                keyProcessed = false;
                System.out.println("释放...");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    public void nativeKeyTyped(NativeKeyEvent e) {
    }
}